package com.itrh.org.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.itrh.auth.dto.LoginDTO;
import com.itrh.base.service.impl.BaseServiceImpl;
import com.itrh.org.domain.Department;
import com.itrh.org.domain.Employee;
import com.itrh.org.mapper.EmployeeMapper;
import com.itrh.org.query.DepartmentQuery;
import com.itrh.org.query.EmployeeQuery;
import com.itrh.org.service.IDepartmentService;
import com.itrh.org.service.IEmployeeService;
import com.itrh.org.util.EmployeeOfMode;
import com.itrh.org.util.LoginMap;
import com.itrh.org.util.Result;
import com.itrh.org.util.pageResult;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * ClassName: IEmployeeServiceImpl
 *
 * @author XHU_WHY
 * @version V1.0
 * @since 2024/4/2 16:41
 */
@Service
public class IEmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {
    @Resource
    private EmployeeMapper employeeMapper;
    @Resource
    private IDepartmentService departmentService;

    @Override
    @Transactional
    public Result saveOrUpdate(Employee employee) {
        try {
            if (employee.getId() == null) {
                employee.setHeadImage("https://th.bing.com/th?id=OIP.m--751RSKkOTO8ZxoEK4WQAAAA&w=250&h=250&c=8&rs=1&qlt=90&o=6&dpr=1.3&pid=3.1&rm=2");
                employeeMapper.insert(employee);
            } else {
                employeeMapper.update(employee);
            }
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("操作失败");
        }
    }

    @Override
    public Result login(LoginDTO loginDTO) {
        Employee employee = employeeMapper.selectByUserName(loginDTO.getUsername());
        if (employee == null || !employee.getPassword().equals(loginDTO.getPassword())) {
            return Result.error("用户名或密码错误");
        } else {
            Map<String, Employee> loginMap = LoginMap.getLoginMap();
            // 生成token
            String token = UUID.randomUUID().toString();
            loginMap.put(token, employee);
            Map<String, Object> map = new HashMap<>();
            map.put("token", token);
            map.put("user", employee);
            return Result.success(map);
        }
    }

    @Override
    @Transactional
    public void importEmployee(MultipartFile file, HttpServletResponse response) throws Exception {
        ImportParams params = new ImportParams();
        params.setNeedVerify(true);
        ExcelImportResult<EmployeeOfMode> result = ExcelImportUtil.importExcelMore(file.getInputStream(), EmployeeOfMode.class, params);
        List<EmployeeOfMode> failList = result.getFailList();
        if (failList.size() > 0) {
            List<ExcelExportEntity> list = new ArrayList<>();
            for (int i = 0; i < failList.size(); i++) {
                EmployeeOfMode employeeOfMode = failList.get(i);
                // 导出员工数据
                ExcelExportEntity entity = new ExcelExportEntity("用户名", "username");
                list.add(entity);
                list.add(new ExcelExportEntity("密码", "password"));
                list.add(new ExcelExportEntity("邮箱", "email"));
                list.add(new ExcelExportEntity("年龄", "age"));
                list.add(new ExcelExportEntity("头像", "headImage"));
                list.add(new ExcelExportEntity("部门名称", "department.name"));
                list.add(new ExcelExportEntity("错误信息", "errorMsg"));
                Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("错误数据", "错误数据"), list, failList);
                response.setHeader("code", "0");
                workbook.write(response.getOutputStream());
            }
        }
        List<Employee> empList = ExcelImportUtil.importExcel(file.getInputStream(), Employee.class, params);
        // 根据部门名称查询部门id
        empList.forEach(employee -> {
            Department department = employee.getDepartment();
            Department query = departmentService.selectByName(department.getName());
            department.setId(query.getId());
        });
        employeeMapper.batchSave(empList);
    }

    @Override
    public void exportEmployee(String name, HttpServletResponse response) throws IOException {
        // 导出员工数据
        List<ExcelExportEntity> list = new ArrayList<>();
        ExcelExportEntity entity = new ExcelExportEntity("用户名", "username");
        list.add(entity);
        list.add(new ExcelExportEntity("密码", "password"));
        list.add(new ExcelExportEntity("邮箱", "email"));
        list.add(new ExcelExportEntity("年龄", "age"));
        list.add(new ExcelExportEntity("头像", "headImage"));
        list.add(new ExcelExportEntity("部门名称", "department.name"));
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("员工数据", "员工数据"), list, employeeMapper.export(name));
        response.setCharacterEncoding("UTF-8");
        response.setHeader("content-Type", "application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;filename=testExport.xls");
        workbook.write(response.getOutputStream());
    }
}
